package com.fulizhe.catlocal.integration.springboot.config;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import com.dianping.cat.Cat;
import com.dianping.cat.local.integration.mybatis.CatMybatisPlugin;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;

@Intercepts({
		@Signature(method = "query", type = Executor.class, args = { MappedStatement.class, Object.class,
				RowBounds.class, ResultHandler.class }),
		@Signature(method = "query", type = Executor.class, args = { MappedStatement.class, Object.class,
				RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class }),
		@Signature(method = "update", type = Executor.class, args = { MappedStatement.class, Object.class }) })
public class CatMybatisPluginEx extends CatMybatisPlugin implements Interceptor {
	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = this.getStatement(invocation);
		String methodName = this.getMethodName(mappedStatement);
		Transaction t = Cat.newTransaction("SQL", methodName);
		Cat.logEvent("LAYER", "Dao-Mybatis");

		String sql = this.getSql(invocation, mappedStatement);
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Cat.logEvent("SQL.Method", sqlCommandType.name().toLowerCase(), Message.SUCCESS, sql);

		String url = this.getSQLDatabaseUrlByStatement(mappedStatement);
		Cat.logEvent("SQL.Database", url);

		return doFinish(invocation, t);
	}
}
